<?php
namespace backend\controllers;

use app\models\User;
use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;

/**
 * Site controller
 */
class SiteController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['index', 'logout'],
                'rules' => [

                    [
                        'allow' => true,
                        'actions' => ['logout','index'],
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    public function actionIndex(){
        return $this->render("index");
    }
    /**
     * Login action.
     *
     * @return string
     */
    public function actionLogin()
    {
        $this->layout="layout";
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }else{
            return $this->render("login");
        }

    }

    public function actionSignUp(){

        $request = Yii::$app->request;
        if ($request->isAjax){
            $username = $request->post("username");
            $password = $request->post("password");
            $user = User::findOne(['username'=>$username]);
            //密码校验
            if($user){
                if(Yii::$app->security->validatePassword($password,$user->password)){
                    Yii::$app->user->login($user);
                    $return['status']=true;

                }else{
                    $return['status']=false;
                    $return['msg']="用户名或密码错误";

                }
            }else{
                $return['status']=false;
                $return['msg']="用户名或密码错误";


            }
            return json_encode($return);
        }
    }
    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }
}
